#include "cSharedMemory.h"
#include <ctype.h>
#include <unistd.h>

void* mmCreateOnOpen(char* name, int size, int* out_flag)
{
    void *out_shmp = NULL;
    /* Create shared memory object and set its size */
    /* O_EXCL If O_CREAT was also specified, and a shared memory object
              with the given name already exists, return an error.  The
              check for the existence of the object, and its creation if
              it does not exist, are performed atomically.*/
    int fd = shm_open(name, O_CREAT | O_EXCL | O_RDWR, 0666);
    if(fd == -1) {
        *out_flag = -1;
        return NULL;
    }

    if (ftruncate(fd, size) == -1) {
        *out_flag = -2;
        return NULL;
    }

    /* Map the object into the caller's address space. */

    out_shmp = mmap(NULL, size, PROT_READ | PROT_WRITE,
                MAP_SHARED, fd, 0);
    if (out_shmp == MAP_FAILED) {
        *out_flag = -3;
        return NULL;
    }        

    *out_flag = 0;
    return out_shmp;
}

void* mmOpen(char* name, int size, int* out_flag)
{
    void *out_shmp = NULL;
    int fd = shm_open(name, O_RDWR, 0);
    if (fd == -1) 
    {
        *out_flag = -1;
        return NULL;
    }
    out_shmp = mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
    if (out_shmp == MAP_FAILED)
    {
        *out_flag = -2;
        return NULL;
    }

    *out_flag = 0;
    return out_shmp;
}

void mmUnlink(char* name)
{
    shm_unlink((const char*)name);
}